import {Base} from "../../utils/base.js";

class Cart extends Base {

    constructor(){
        super();
        this._storageKeyName = 'cart';
    }

    // 添加商品到购物车
    addCart(item,counts){
        var cartData = this.getCartDataFromLocal();
        var isHasInfo = this._isHasThatOne(item.id,cartData);
        // console.log(isHasInfo);
        if(isHasInfo.index == -1){
            item.counts = counts;
            item.selectStatus = true;
            cartData.push(item);
        }else{
            // console.log(cartData);
            cartData[isHasInfo.index].counts += counts;
        }       
        this.execSetStorageSync(cartData);
    }

    // 缓存购物车数据
    execSetStorageSync(data){
        wx.setStorageSync(this._storageKeyName, data);
    }

    // 获取缓存中的购物车数据
    getCartDataFromLocal(flag){
        var res = wx.getStorageSync(this._storageKeyName);
        if(!res){
            res = [];
        }
        if(flag){
            var newRes = [];
            for(let i = 0; i < res.length; i++){
                if(res[i].selectStatus){
                    newRes.push(res[i]);
                }
            }
            res = newRes;
        }
        return res;
    }

    _isHasThatOne(id,arr){
        var item;
        var result = {index:-1};
        for(let i = 0; i < arr.length; i++){
            item = arr[i];
            if(item.id == id){
                result = {index:i, data:item}
            }
            // break;
        }
        return result;
     }
     
    //  获取购物车商品总数量
    // flag为true 考虑商品选择状态
     getCartTotalCounts(flag){
        var cartList = this.getCartDataFromLocal();
        var counts = 0;
        for(let i = 0; i < cartList.length; i++){
            if(flag){
                if(cartList[i].selectStatus){
                    counts += cartList[i].counts;
                }
            }else{
                counts += cartList[i].counts;
            }           
        }
        return counts;
     }
}
export{Cart};